package com.example.beatbox;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.loader.content.Loader;

public class BeatBox {

    private static final String TAG = "BeatBox";

    private static final String SOUNDS_FOLDER = "sample_sounds";

    private static final int MAX_SOUNDS = 5;
    private SoundPool mSoundPool;

    private AssetManager assetManager;
    private List<Sound> mSounds = new ArrayList<>();
    public BeatBox(Context context){
        assetManager = context.getAssets();
        mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC,0);
        loadSounds();
    }


    private void loadSounds(){
        String[] soundsNames = {};
        try{
            soundsNames = assetManager.list(SOUNDS_FOLDER);
            Log.i(TAG,"Found "+soundsNames.length+" sounds");
        }catch (IOException e){
            Log.e(TAG,"Could not list assets",e);
        }

        for(String fileName:soundsNames){
            String assetPath = SOUNDS_FOLDER+"/"+fileName;
            Sound sound = new Sound(assetPath);
            try {
                load(sound);
            } catch (IOException e) {
                Log.e(TAG,"Could not load sound "+fileName);
            }
            mSounds.add(sound);
        }
    }

    private void load(Sound sound) throws IOException {
        AssetFileDescriptor assetFileDescriptor = assetManager.openFd(
                sound.getmAssetsPath());
        int soundId = mSoundPool.load(assetFileDescriptor,1);
        sound.setSoundId(soundId);
    }

    public List<Sound> getSounds(){
        return mSounds;
    }

    public void play(Sound sound){
        Integer soundId = sound.getSoundId();
        if(soundId == null){
            return;
        }

        mSoundPool.play(soundId,1.0f,1.0f,1,0,1.0f);
    }
    public void release(){
        mSoundPool.release();
    }

    public void setRate(Sound sound,float rate){
        Integer soundId = sound.getSoundId();
        if(soundId == null || rate <=0||rate>2){
            return;
        }
        mSoundPool.setRate(soundId,rate);
    }


}
